<template>
  <el-dialog
    :title="dialogObj.title"
    append-to-body
    :visible.sync="dialogObj.show"
    :close-on-click-modal="false"
    width="700px"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="120px"
      :rules="rules"
      :disabled="dialogObj.read"
      v-if="dialogObj.show"
      status-icon
    >
      <el-form-item label="账号：" prop="loginAccount">
        <el-input
          v-model="form.loginAccount"
          style="width:200px;"
          size="mini"
          :disabled="dialogObj.id != ''"
          maxlength="20"
          :placeholder="placeholderTips.userName"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="密码："
        prop="loginPassword"
        v-if="dialogObj.id == ''"
      >
        <el-input
          v-model="form.loginPassword"
          style="width:200px;"
          size="mini"
          maxlength="20"
          :placeholder="placeholderTips.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名：" prop="userName">
        <el-input
          v-model="form.userName"
          style="width:200px;"
          size="mini"
          maxlength="20"
          :placeholder="placeholderTips.userName"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input
          v-model="form.email"
          style="width:200px;"
          size="mini"
          maxlength="50"
          placeholder="请输入邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input
          v-model="form.phone"
          style="width:200px;"
          size="mini"
          maxlength="20"
          :placeholder="placeholderTips.phone"
        ></el-input>
      </el-form-item>
      <el-form-item label="代理商：" prop="organizationId">
        <el-select
          v-model="form.organizationId"
          placeholder="选择代理商"
          size="mini"
        >
          <el-option
            v-for="(data, index) in agentList"
            :key="index"
            :label="data.name"
            :value="data.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色类型：" prop="userRoleId">
        <el-select
          v-model="form.userRoleId"
          placeholder="请选择类型"
          size="mini"
          value-key="index"
          @change="selectRoleOption"
        >
          <el-option
            v-for="(item, index) in RoleSelectList"
            :key="index"
            :label="item.name"
            :value="item.roleId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上级：" prop="superiorId">
        <el-select
          v-model="form.superiorId"
          placeholder="请选择"
          size="mini"
          @change="selectSuperiorOption"
        >
          <el-option
            v-for="data in isAgent"
            :key="data.userId"
            :label="data.userName"
            :value="data.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="userState">
        <el-select
          v-model="form.userState"
          placeholder="请选择"
          size="mini"
          @change="selectUserState"
        >
          <el-option
            v-for="data in userStatusList"
            :key="data.id"
            :label="data.value"
            :value="data.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input
          type="textarea"
          v-model="form.remark"
          style="width:400px;"
          size="mini"
          maxlength="100"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="sub" size="mini">确 定</el-button>
      <el-button @click="dialogObj.show = false" size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { _debounce } from "@u/debounce";
import { USERSTATUSLIST } from "@u/wordbook";
import {
  placeholderTips,
  validateUserName,
  validatePhone,
  validateUserPassword,
  validateTemplate,
  validateName,
  validateEmail,
} from "./validate";
import {
  getRoleSelectApi,
  AddUserApi,
  updateUserApi,
  getSysuserSelectApi,
  getAgentPageApi
} from "@s/api";
export default {
  name: "dialogCom",
  props: ["dialogObj"],
  data() {
    return {
      isAgent: [],
      agentStatus: true,
      placeholderTips: placeholderTips,
      form: {
        userId: undefined,
        loginAccount: "",
        loginPassword: "",
        userName: "",
        userRoleId: "",
        phone: "",
        email: "",
        superiorId: "",
        remark: "",
        userState: "",
        organizationId: ""
      },
      userStatusList: USERSTATUSLIST,
      agentList: [],
      // loginAccountName: "",
      RoleSelectList: [],
      rules: {
        loginAccount: [
          { required: true, trigger: "blur", message: "请输入账号" },
          { validator: validateUserName },
        ],
        organizationId: [
          { required: true, message: "代理商", trigger: "blur" },
          { validator: validateTemplate },
        ],
        loginPassword: [
          { required: true, trigger: "blur", message: "请输入密码" },
          { validator: validateUserPassword },
        ],
        userName: [
          { required: true, trigger: "blur", message: "请输入用户名" },
          { validator: validateName },
        ],
        email: [{ validator: validateEmail }],
        userRoleId: [
          { required: true, message: "请选择角色类型", trigger: "blur" },
          { validator: validateTemplate },
        ],
        phone: [
          { required: true, trigger: "blur", message: "请输入手机号" },
          { validator: validatePhone },
        ],
        superiorId: [
          { required: true, message: "请选择上级", trigger: "blur" },
          { validator: validateTemplate },
        ],
        userState: [
          { required: true, message: "请选择用户状态", trigger: "blur" },
          { validator: validateTemplate },
        ],
      },
    };
  },
  mounted() {
    this.getRoleSelect();
    this.getAgentSelect();
    // let userInfo = JSON.parse(localStorage.getItem("mb_userInfo")) || "{}";
    // this.loginAccountName = userInfo.loginAccount
  },
  methods: {
    // 角色信息
    getRoleSelect() {
      getRoleSelectApi().then((res) => {
      const newRes =  res.filter(item => {
          return item.name !=="超级管理员"
        })
        this.RoleSelectList = newRes;
      });
    },
    getSysuserSelect(val) {
      getSysuserSelectApi({ roleIds: [val] }).then((res) => {
        this.isAgent = res;
      });
    },
    selectSuperiorOption(val) {
      this.form.superiorId = val;
    },
    selectUserState(val) {
      this.form.userState = val;
    },
    // 代理商集合
    getAgentSelect() {
      getAgentPageApi().then(res => {
        this.agentList = res.list;
      });
    },

    initDialog() {
      if (this.dialogObj.id) {
        this.form.userId = this.dialogObj.id;
        this.form.loginAccount = this.dialogObj.form.loginAccount;
        this.form.loginPassword = this.dialogObj.form.loginPassword;
        this.form.userName = this.dialogObj.form.userName;
        this.form.phone = this.dialogObj.form.phone;
        this.form.email = this.dialogObj.form.email;
        this.form.userRoleId = this.dialogObj.form.userRoleId;
        this.form.superiorId = this.dialogObj.form.superiorId;
        this.form.organizationId = this.dialogObj.form.organizationId;
        this.form.remark = this.dialogObj.form.remark;
        this.form.userState = this.dialogObj.form.userState;
        this.RoleSelectList.forEach((item) => {
          if (item.roleId == this.dialogObj.form.userRoleId) {
            this.getSysuserSelect(item.parentId);
          }
        });
      } else {
        this.form.loginAccount = "";
        this.form.loginPassword = "";
        this.form.userName = "";
        this.form.phone = "";
        this.form.email = "";
        this.form.userRoleId = "";
        this.form.superiorId = "";
        this.form.remark = "";
        this.form.userState = 1;
      }
    },
    sub: _debounce(function() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dialogObj.id) {
            this.updateSub();
          } else {
            this.addSub();
          }
        }
      });
    }),
    updateSub() {
      let json = JSON.parse(JSON.stringify(this.form));
      if (json.activityIds instanceof Array) {
        json.activityIds = json.activityIds.join(",");
        var arr = [];
        this.form.activityIds.forEach(v => {
          this.ActivityList.forEach(item => {
            if (v == item.id) {
              arr.push(item.activityName);
            }
          });
        });
        json.activityNames = arr.join(",");
      }
      if (json.loginPassword == this.dialogObj.form.loginPassword) {
        json.loginPassword = "";
      }
      updateUserApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "修改成功！"
        });
      });
    },
    addSub() {
      let json = JSON.parse(JSON.stringify(this.form));
      if (json.activityIds instanceof Array) {
        json.activityIds = json.activityIds.join(",");
        var arr = [];
        this.ActivityList.forEach(item => {
          this.form.activityIds.forEach(v => {
            if (v == item.id) {
              arr.push(item.activityName);
            }
          });
        });
        json.activityNames = arr.join(",");
      }
      AddUserApi(json).then(() => {
        this.dialogObj.show = false;
        this.$emit("reflash");
        this.$message({
          type: "success",
          message: "添加成功！"
        });
      });
    },

    selectRoleOption(val) {
      this.form.userRoleId = val;
      this.form.superiorId = "";
      this.RoleSelectList.forEach(item => {
        if (item.roleId == val) {
          this.getSysuserSelect(item.parentId);
        }
      });
    }
  },
  watch: {
    "dialogObj.show"(val) {
      if (val) {
        this.initDialog();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  color: #409eff !important;
  font-weight: 700 !important;
}
</style>
